/*
 * Copyright (C) ZHANG Xin
 * LICENSE: MIT
 */

#include <Python.h>
#include <ngx_http.h>
#include <ngx_http_asgi_handler.h>

static u_char *
execute_python_script(PyObject* asgi_app, ngx_pool_t *pool) {
    u_char *rt = NULL;
    PyObject *pArgs, *pValue;
    pArgs = PyTuple_New(0);
    pValue = PyObject_CallObject(asgi_app, pArgs);
    Py_DECREF(pArgs);
    if (pValue == NULL) {
        Py_DECREF(pValue);                   
        rt = ngx_pcalloc(pool, (256) * sizeof(u_char));
        ngx_sprintf(rt, "{\"error\":\"result is NULL\"}");
    } else {
        rt = (u_char *) PyUnicode_AsUTF8(pValue);
    }

    return rt;
}

ngx_int_t 
ngx_http_asgi_handler(ngx_http_request_t *r) {
    ngx_int_t    rc;
    ngx_buf_t   *b;
    ngx_chain_t  out;
    ngx_http_asgi_conf_t* cf = ngx_http_get_module_loc_conf(r, ngx_http_asgi_module);

    PyObject* asgi_app = cf->asgi_app;
    if (asgi_app == NULL) {
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    u_char *ngx_asgi_json = execute_python_script(
        asgi_app,
        r->pool
    );

    ngx_uint_t content_length = ngx_strlen(ngx_asgi_json);

    /* we response to 'GET' requests only */
    if (!(r->method & (NGX_HTTP_GET))) {
        return NGX_HTTP_NOT_ALLOWED;
    }

    /* discard request body, since we don't need it here */
    rc = ngx_http_discard_request_body(r);

    if (rc != NGX_OK) {
        return rc;
    }

    ngx_str_set(&r->headers_out.content_type, "application/json");


    /* allocate a buffer for your response body */
    b = ngx_pcalloc(r->pool, sizeof(ngx_buf_t));
    if (b == NULL) {
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }

    /* attach this buffer to the buffer chain */
    out.buf = b;
    out.next = NULL;

    /* adjust the pointers of the buffer */
    b->pos = ngx_asgi_json;
    b->last = ngx_asgi_json + content_length;
    b->memory = 1;    /* this buffer is in memory */
    b->last_buf = 1;  /* this is the last buffer in the buffer chain */

    /* set the status line */
    r->headers_out.status = NGX_HTTP_OK;
    r->headers_out.content_length_n = content_length;

    /* send the headers of your response */
    rc = ngx_http_send_header(r);

    if (rc == NGX_ERROR || rc > NGX_OK || r->header_only) {
        return rc;
    }

    /* send the buffer chain of your response */
    return ngx_http_output_filter(r, &out);
}
